package com.cnbot.printer;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;

import com.smartdevicesdk.btprinter.BluetoothService;
import com.smartdevicesdk.btprinter.ICoallBack;
import com.smartdevicesdk.btprinter.PrintService;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Copyright (c) 2016--2019/3/14  Hunan Cnbot Co., Ltd. All Rights Reserved.
 *
 * @descriptoin 打印机工具类
 * @FileName: PrinterApi.java
 * @author: dc
 * @date: 2019/3/14 15:25
 * @version: 1.0
 */

public class PrinterApi {

    private static PrinterApi instance;
    /**
     * 设备的mac地址
     */
    private final String EXTRA_DEVICE_ADDRESS = "device_address";
    /**
     * 打印机的蓝牙名称
     */
    private String deviceName = "ZKCBTMV1";

    /**
     * 搜索新的设备
     */
    private List<String> mNewDevicesArrayAdapter = new ArrayList<>(16);

    /**
     * 打印机各种状态
     */
    private IPrintListener iPrintListener;
    /**
     * 打印服务类
     */
    private PrintService printService;

    /**
     * 广播接受者标识位
     */
    private boolean mReceiverTag = false;
    /**
     * 蓝牙扫描广播
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            mReceiverTag = true;
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName());
                    if (device.getName() != null) {
                        if (device.getName().equals(deviceName)) {
                            //直接连接该设备
                            connectDevice(device);
                            return;
                        }
                    }
                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (!mNewDevicesArrayAdapter.contains(deviceName)) {
                    if (!objNull(iPrintListener)) {
                        iPrintListener.deviceNotFound();
                    }
                }
            }
        }
    };
    /**
     * 保存连接成功的设备地址
     */
    private String macAddressStr;
    /**
     * 蓝牙适配器
     */
    private BluetoothAdapter mBtAdapter;
    /**
     * 上下文
     */
    private Context mContext;

    public PrinterApi(Context context) {
        mContext = context;
    }

    public synchronized static PrinterApi getInstance(Context context) {
        if (instance == null) {
            synchronized (PrinterApi.class) {
                if (instance == null) {
                    instance = new PrinterApi(context);
                }
            }
        }
        return instance;
    }

    /**
     * 设置需要寻找的打印机名称
     *
     * @param deviceName
     */
    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
    }

    /**
     * 查找打印机设备 3
     *
     * @return
     */
    public void scanPrinterDevice() {
        initBlue();
        // Register for broadcasts when a device is discovered
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        mContext.registerReceiver(mReceiver, filter);

        // Register for broadcasts when discovery has finished
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        mContext.registerReceiver(mReceiver, filter);
    }

    /**
     * 初始化蓝牙
     *
     * @return
     */
    private void initBlue() {
        //搜索设备
        // Get the local Bluetooth adapter
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();

        // Get a set of currently paired devices
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

        // If there are paired devices, add each one to the ArrayAdapter
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                if (device.getName().equals("ZKCBTMV1")) {
                    connectDevice(device);
                }
            }
        } else {
            String noDevices = "no paired device";
            startScan();
        }
    }

    /**
     * 连接打印机设备
     *
     * @param device
     */
    private void connectDevice(BluetoothDevice device) {
        if (!objNull(printService)) {
            //直接连接该设备
            try {
                Intent intent = new Intent();
                intent.putExtra(EXTRA_DEVICE_ADDRESS, device.getAddress().trim());
                printService.connectDevice(intent, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断对象是否为空
     *
     * @param o
     * @return
     */
    public boolean objNull(Object o) {
        if (o == null) {
            return true;
        }
        return false;
    }

    /**
     * 搜索蓝牙设备
     */
    private void startScan() {
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }
        // Request discover from BluetoothAdapter
        mBtAdapter.startDiscovery();
    }

    /**
     * 初始化设备  1
     */
    public void initPrintDevice() {
        printService = new PrintService(mContext);
    }

    /**
     * 自定义控件的自定义事件  2
     *
     * @param listener
     */
    public void setPrintDevice(IPrintListener listener) {
        if (!objNull(printService)) {
            iPrintListener = listener;
            printService.setOnPrinterStatus(new PrintStatusCallback());
        }
    }

    /**
     * 打印文字
     *
     * @param str
     */
    public void printerText(String str) {
        if (!objNull(printService)) {
            printService.printText(str);
        }
    }

    /**
     * 打印二维码
     *
     * @param sr
     */
    public void printerQrCode(String sr) {
        if (!objNull(printService)) {
            printService.printQrCode(sr);
        }
    }

    /**
     * 打印图片
     *
     * @param bitmap
     */
    public void printerImage(Bitmap bitmap) {
        if (!objNull(printService)) {
            printService.printRasterImage(bitmap);
        }
    }

    /**
     * 设置打印语言
     *
     * @param language
     * @param languageCode
     */
    public void setPrinterLanguage(String language, int languageCode) {
        if (!objNull(printService)) {
            printService.setPrint_Language(language, languageCode);
        }
    }

    /**
     * 断开设备连接
     */
    public void disConnectDevice() {
        if (!objNull(printService)) {
            printService.disconnect();
        }
        // Make sure we're not doing discovery anymore
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }

        // Unregister broadcast listeners
        if (mReceiver != null && mReceiverTag) {
            mContext.unregisterReceiver(mReceiver);
        }
        mReceiverTag = false;

    }

    class PrintStatusCallback implements ICoallBack {
        String text = "";

        @Override
        public void onPrinterStatus(int s, String string) {
            switch (s) {
                case BluetoothService.STATE_CONNECTED:
                    // 连接成功蜂鸣器发声
                    printService.write(PrintCommand.set_Buzzer(2, 1));

                    // 连接成功
                    text += "\r\n"
                            + "连接成功";

                    macAddressStr = printService.getMacAddress();
                    text += "\r\n" + macAddressStr;
                    if (!objNull(iPrintListener)) {
                        iPrintListener.connected();
                    }
                    break;
                case BluetoothService.STATE_CONNECTING:
                    // 正在连接
                    text += "\r\n"
                            + "正在连接";
                    if (!objNull(iPrintListener)) {
                        iPrintListener.connecting();
                    }
                    break;
                case BluetoothService.STATE_LISTEN:
                case BluetoothService.STATE_NONE:
                    // 未连接
                    text += "\r\n"
                            + "未连接";
                    if (!objNull(iPrintListener)) {
                        iPrintListener.connectNone();
                    }
                    break;
                case BluetoothService.READ_DATA:
                    // 打印机返回数据

                    break;
                default:

                    break;
            }
        }
    }


}
